package com.huowenjie.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.huowenjie.entity.User;
import com.huowenjie.entity.UserExample;
import com.huowenjie.mapper.UserMapper;
import com.huowenjie.util.Md5Util;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class UserController {

    @Autowired
    UserMapper userMapper;

    @RequestMapping("userList")
    public PageInfo<User> userList(@RequestParam(defaultValue = "0")Integer pageNum){

        System.out.println(pageNum);
        PageHelper.startPage(pageNum,3);

        UserExample userExample = new UserExample();
        List<User> userList = userMapper.selectByExample(userExample);

        PageInfo<User> userPageInfo = new PageInfo<>(userList);

        return userPageInfo;
    }

    @RequestMapping("register")
    public String register(@RequestBody User user){

        String psw = Md5Util.md5Encoding(user.getPsw());
        user.setPsw(psw);

        userMapper.insert(user);

        return "success";
    }

    @RequestMapping("login")
    public String login(@RequestBody User user){
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();
        criteria.andUnameEqualTo(user.getUname());
        criteria.andPswEqualTo(user.getPsw());
        List<User> userList = userMapper.selectByExample(userExample);
        if(userList!=null&&userList.size()>0){
            return userList.get(0).getUid()+"";
        }
        return "";
    }

}
